package com.bj.ocean.gankio;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bj.ocean.gankio.constant.Constants;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestWebActivity extends BaseActivity {

    private WebView wv;
    private TextView tvTitle;
    private LinearLayout ll_Empty;
    private  boolean isLoadError;
    private TextView btn_back;
    private ProgressBar progressBar;
    private String failUrl="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_web);

        wv=findViewById(R.id.web_view);
        tvTitle=findViewById(R.id.tv_title);
        ll_Empty=findViewById(R.id.ll_empty);
        btn_back=findViewById(R.id.btn_back);
        progressBar=findViewById(R.id.pb);
        initWeb();
        initListener();
        initData();
    }

    private void initListener() {

        ll_Empty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (NetworkUtil.isNetworkConnect(TestWebActivity.this)){
                    hideOrShowWeb(false);
                    if (!TextUtils.isEmpty(failUrl)){
                        wv.loadUrl(failUrl);
                        return;
                    }
                    wv.reload();
                }else {
                    showToast("检查网络");
                }
            }
        });
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtil.isNetworkConnect(TestWebActivity.this)){
                    if (wv.canGoBack()){
                        wv.goBack();
                    }else {
                        finish();
                    }
                }else {
                    finish();
                }
            }
        });
    }

    private void initData() {

        tvTitle.setText("我是默认标题");
        if (NetworkUtil.isNetworkConnect(this)){
            wv.loadUrl(Constants.URL_03);
        }else {
            hideOrShowWeb(true);
        }
    }

    private void initWeb() {

        wv.getSettings().setBuiltInZoomControls(false);
        wv.getSettings().setSupportZoom(false);
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.getSettings().setTextZoom(100);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        wv.getSettings().setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        wv.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);// 实现8倍缓存
        wv.getSettings().setAllowFileAccess(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);//  缓存模式
        wv.getSettings().setBlockNetworkImage(false);//解决图片不显示
        String appCachePath = getApplication().getCacheDir().getAbsolutePath();
        wv.getSettings().setAppCachePath(appCachePath);
        wv.getSettings().setDatabaseEnabled(true);
        wv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            wv.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        setFileAccess(wv);
        wv.setWebViewClient(new GmWebClient());
        wv.setWebChromeClient(new GmWebChromeClient());

    }

    private void setFileAccess(WebView webView) {
        try {
            if (Build.VERSION.SDK_INT < 16) {
                Class<?> clazz = webView.getSettings().getClass();
                Method method = clazz.getMethod(
                        "setAllowUniversalAccessFromFileURLs", boolean.class);//利用反射机制去修改设置对象
                if (method != null) {
                    method.invoke(webView.getSettings(), false);//修改设置
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private class GmWebClient extends WebViewClient {
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError errorResponse) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                Log.e(TAG, "onReceivedError: ");
                handlerError(view,
                        errorResponse.getErrorCode() + "",
                        errorResponse.getDescription().toString(),
                        request.getUrl().toString());
            }
            super.onReceivedError(view, request, errorResponse);
        }
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                Log.i("gomepaystate", "onReceivedError");
                handlerError(view, errorCode + "", description, failingUrl);
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            String title=view.getTitle();
            if (isLoadError){
                hideOrShowWeb(true);
            }else {
                if (!isErrorTitle(title,url)){
                    tvTitle.setText(title);
                }

                hideOrShowWeb(false);
            }
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            isLoadError=false;
            super.onPageStarted(view, url, favicon);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }
    }

    private boolean isErrorTitle(String title,String url) {

        if (TextUtils.isEmpty(title) || title.startsWith("http://") || title.startsWith("https://"))
            return true;

        Uri uri = Uri.parse(url);
        String path = uri.getPath();
        String hostName = uri.getHost();

        String failTitle = "";

        if (!TextUtils.isEmpty(hostName))
            failTitle = hostName;
        if (!TextUtils.isEmpty(path))
            failTitle += path;

        String failTitleFinal = failTitle;

        String titleTemp = title;
        if (!TextUtils.isEmpty(failTitle) && failTitle.endsWith("/"))
            failTitleFinal = failTitle.substring(0, failTitle.length() - 1);

        if (!TextUtils.isEmpty(title) && title.endsWith("/"))
            titleTemp = title.substring(0, title.length() - 1);

//        MethodUtils.myLog("fail_title:" + failTitleFinal + "--title--" + titleTemp);

        return "about:blank".equals(title) && !failTitleFinal.equals(titleTemp);

    }

    private void handlerError(WebView view, String s, String description, String failingUrl) {


        failUrl=failingUrl;
        try {
            view.stopLoading();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        try {
            view.clearView();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        view.loadUrl("about:back");   //  关键代码，这里是加载系统空白页
        isLoadError=true;

    }

  private void hideOrShowWeb(boolean f){
      Log.e(TAG, "hideOrShowWeb: "+f );
       if (f){
          wv.setVisibility(View.GONE);
          ll_Empty.setVisibility(View.VISIBLE);
       }else {
           wv.setVisibility(View.VISIBLE);
           ll_Empty.setVisibility(View.GONE);
       }
   }

    private class GmWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

        }
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);

            if(newProgress ==100){
                progressBar.setVisibility(View.GONE);
                //progressBar.setProgress(newProgress);
            }else {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);//设置加载进度
            }
        }
    }
}
